﻿/*
Copyright (c) 2013, Marc Tanti
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the www.marctanti.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MARIA.level.situation;
using MARIA.program.statementfactory;
using MARIA.program.statement;
using System.Drawing;
using MARIA.level.square;

namespace MARIA.level
{
    [Serializable]
    /// <summary>
    /// A level of the game.
    /// </summary>
    public class Level
    {

        /// <summary>
        /// The id of the level.
        /// </summary>
        public int ID
        {
            get
            {
                return id;
            }
        }
        private int id;

        /// <summary>
        /// The title of the level.
        /// </summary>
        public string Title
        {
            get
            {
                return title;
            }
        }
        private string title;

        /// <summary>
        /// The description of the level.
        /// </summary>
        public string Description
        {
            get
            {
                return description;
            }
        }
        private string description;

        /// <summary>
        /// Situations available.
        /// </summary>
        public Situation[] Situations
        {
            get
            {
                return situations;
            }
        }
        private Situation[] situations;

        /// <summary>
        /// Statement list.
        /// </summary>
        public StatementFactory[] StatementList
        {
            get
            {
                return statementList;
            }
        }
        private StatementFactory[] statementList;

        /// <summary>
        /// Program to modify.
        /// </summary>
        public Statement Program
        {
            get
            {
                return program;
            }
            set
            {
                program = value;
            }
        }
        private Statement program;

        /// <summary>
        /// Initialize a new instance of Level from a situation list, a statement list and a program.
        /// </summary>
        /// <param name="id">The unique id of the level.</param>
        /// <param name="title">The title of the level.</param>
        /// <param name="description">The description of the level.</param>
        /// <param name="situations">Situation list.</param>
        /// <param name="statementList">Statement list.</param>
        /// <param name="program">Program to modify.</param>
        public Level(int id, string title, string description, Situation[] situations, StatementFactory[] statementList, Statement program)
        {
            this.id = id;
            this.title = title;
            this.description = description;
            this.situations = situations;
            this.statementList = statementList;
            this.program = program;
        }

        /// <summary>
        /// Initialize a new instance of Level based on a description in a file.
        /// </summary>
        /// <param name="fileContent">The content of the file.</param>
        /// <param name="availableSquares">A list of squares which can be used.</param>
        /// <param name="availableStatements">A list of statements which can be used.</param>
        public Level(string fileContent, Square[] availableSquares, StatementFactory[] availableStatements)
        {
            string[] lines = fileContent.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            int currIndex = 0;

            //id
            this.id = int.Parse(lines[currIndex]);

            //title
            currIndex++;
            currIndex++;
            this.title = lines[currIndex];

            //description
            currIndex++;
            currIndex++;
            this.description = "";
            while (!lines[currIndex].Equals("---"))
            {
                description += lines[currIndex] + "\r\n";
                currIndex++;
            }

            //situations
            currIndex++;
            currIndex++;
            List<Situation> situationsLst = new List<Situation>();
            while (!lines[currIndex].Equals("---"))
            {
                if (lines[currIndex].Equals(""))
                {
                    currIndex++;
                }

                //situation name
                string situationName = lines[currIndex];

                //map
                currIndex++;
                Point robotLocation = new Point();
                Square[,] map = new Square[10, 10];
                for (int y = 0; y < 10; y++)
                {
                    for (int x = 0; x < 10; x++)
                    {
                        bool found = false;
                        foreach (Square square in availableSquares)
                        {
                            if (square.CharacterRepresentation.Equals(lines[currIndex][x]))
                            {
                                map[y, x] = square;
                                found = true;
                                break;
                            }
                        }
                        if ('R'.Equals(lines[currIndex][x]))
                        {
                            map[y, x] = ClearSquare.Instance;
                            robotLocation = new Point(x, y);
                            found = true;
                        }

                        if (!found)
                        {
                            throw new ArgumentException();
                        }
                    }
                    currIndex++;
                }

                //max movements
                int maxMovements = int.Parse(lines[currIndex]);

                situationsLst.Add(new Situation(situationName, map, robotLocation, maxMovements));

                currIndex++;
            }
            situations = situationsLst.ToArray();

            //statements
            currIndex++;
            currIndex++;
            List<StatementFactory> statementsLst = new List<StatementFactory>();
            while (!lines[currIndex].Equals("---"))
            {
                bool found = false;
                foreach (StatementFactory statementFactory in availableStatements)
                {
                    if (statementFactory.StatementTextualRepresentation.Equals(lines[currIndex]))
                    {
                        statementsLst.Add(statementFactory);
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    throw new ArgumentException();
                }

                currIndex++;
            }
            statementList = statementsLst.ToArray();

            //program
            this.program = new ProgramStatement("START_HERE");
            Statement prevStatement = program;
            int prevIndent = -1;
            currIndex++;
            currIndex++;
            while (!lines[currIndex].Equals("---"))
            {
                string unindentedLine = lines[currIndex].TrimStart('\t');
                int currIndent = lines[currIndex].Length - unindentedLine.Length;

                Statement statement = null;
                foreach (StatementFactory statementFactory in availableStatements)
                {
                    if (statementFactory.IsDescriptionValid(unindentedLine))
                    {
                        statement = statementFactory.MakeInstance(unindentedLine);
                        break;
                    }
                }
                if (statement == null)
                {
                    throw new ArgumentException();
                }

                //Statement is a child of previous statement
                if (currIndent == prevIndent + 1)
                {
                    Statement parent = prevStatement;
                    if (!parent.CanAdd(statement))
                    {
                        throw new ArgumentException();
                    }
                    parent.Nodes.Add(statement);
                }
                //Statement is a sibling of a previous statement
                else if (currIndent == prevIndent)
                {
                    Statement parent = (Statement)prevStatement.Parent;
                    if (!parent.CanAdd(statement))
                    {
                        throw new ArgumentException();
                    }
                    parent.Nodes.Add(statement);
                }
                //Statement is a sibling of some earlier statement
                else if (currIndent < prevIndent)
                {
                    //Find sibling
                    while (currIndent != prevIndent)
                    {
                        prevStatement = (Statement)prevStatement.Parent;
                        prevIndent--;
                    }

                    Statement parent = (Statement)prevStatement.Parent;
                    if (!parent.CanAdd(statement))
                    {
                        throw new ArgumentException();
                    }
                    parent.Nodes.Add(statement);
                }
                //More than one tab at a time was used
                else
                {
                    throw new ArgumentException();
                }

                prevIndent = currIndent;
                prevStatement = statement;

                currIndex++;
            }
        }

        /// <summary>
        /// Reinitialize all situations.
        /// </summary>
        public void ReinitializeAllSituations()
        {
            foreach (Situation situation in situations)
            {
                situation.Reinitialize();
            }
        }

    }
}
